package com.youbug.kefu.websocket;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.youbug.kefu.constant.AgentConstant;
import com.youbug.kefu.constant.ChatConstant;
import com.youbug.kefu.dto.AgentSessionInfo;
import com.youbug.kefu.entity.Chat;
import com.youbug.kefu.entity.Message;
import com.youbug.kefu.entity.User;
import com.youbug.kefu.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;


/**
 * @author websocket服务
 */
@ServerEndpoint(value = "/agent/{userId}/{chatType}")
@Component
public class AgentWebSocket {

    private static final Logger logger = LoggerFactory.getLogger(AgentWebSocket.class);

    private ObjectMapper objectMapper = new ObjectMapper();
    private static IUserService userService;
    private static IMessageService messageService;
    private static IChatService chatService;
    private static IStateService stateService;
    private static IQueueService queueService;
    private static ISenderService senderService;

    private Random random = new Random();

    @Autowired
    public void setService(IChatService chatService,IMessageService messageService,
                               IUserService userService, IStateService stateService,ISenderService senderService,IQueueService queueService) {
        AgentWebSocket.chatService = chatService;
        AgentWebSocket.messageService = messageService;
        AgentWebSocket.userService = userService;
        AgentWebSocket.stateService = stateService;
        AgentWebSocket.senderService = senderService;
        AgentWebSocket.queueService = queueService;
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") Long userId) {

            QueryWrapper<User> userWp = new QueryWrapper<User>().eq("id", userId);

            userWp.select("username","nick_name");

            User userDb = userService.getOne(userWp);

            ChatsInfoHolder.agentSessionInfoMap.put(userId,
                    new AgentSessionInfo(ChatConstant.AGENT, userId,userDb.getNickName(), session,3, AgentConstant.SINGIN.getCode()));
            queueService.broadcastQueueInfo();
    }

    /**
     * 收到客户端消息后调用的方法
     * 后台收到客户端发送过来的消息
     * onMessage 是一个消息的中转站
     * 接受 浏览器端 socket.send 发送过来的 json数据
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session, @PathParam("userId") Long userId, @PathParam("chatType") String chatType) throws IOException {

        Message msg = objectMapper.readValue(message, Message.class);
        if(ChatConstant.MSG_TYPE_KEEPALIVE.equals(msg.getType())){
            return;
        }
        msg.setSender(ChatConstant.AGENT);
        msg.setSenderId(userId);

        AgentSessionInfo agentSessionInfo = ChatsInfoHolder.agentSessionInfoMap.get(userId);
        Chat chat = agentSessionInfo.getHoldChats().get(msg.getChatId());

        if(ChatConstant.MSG_TYPE_CLOSE.equals(msg.getType())){
            boolean result = senderService.sendMsgToClient(chat.getClientId(), ChatConstant.CLOSE_MSG);
            chatService.closeChat(chat);
        }else{
            boolean save = messageService.save(msg);
            boolean result = senderService.sendMsgToClient(chat.getClientId(), msg);
        }
        session.getBasicRemote().sendText(objectMapper.writeValueAsString(msg));
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session, @PathParam("userId") Long userId) {

//        List<AgentSessionWrapper> agents = ChatsInfoHolder.agents;
//
//        for (int i = 0; i< agents.size(); i++){
//             if(userId.equals(agents.get(i).getUserId())){
//                 AgentSessionWrapper wrapper = agents.get(i);
//                 System.out.println("onClose,座席端断开"+userId);
//                 agents.remove(wrapper);
//             }
//         }
        ChatsInfoHolder.agentSessionInfoMap.remove(userId);
    }

    @OnError
    public void onError(Session session, Throwable error, @PathParam("userId") Long userId) throws IOException {
        System.out.println("agentOnError"+error.getMessage());
        ChatsInfoHolder.agentSessionInfoMap.remove(userId);
        session.close();
    }
}
